<template>
  <!-- 分公司选择 -->
  <a-select v-model="currentValue" v-bind="$attrs" :placeholder="placeholder" v-on="$listeners">
    <a-icon v-if="fetching" slot="suffixIcon" style="color: #096dd9" type="loading" />
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="i in company" :key="i.orgId" selected :value="i.orgId">
      {{ i.orgName }}
    </a-select-option>
  </a-select>
</template>
<script>
import { getAllBranchCompany, getCurrentUserBranchCom2 } from '@/api/commons'
import Vue from 'vue'
/*
 * 2021,8,3排坑，编辑要把autoSelected设为false，新增设为true
 * 否则联动的SelectProject有问题
 *
 *
 *
 *
 *
 * */
export default {
  name: 'SelectSubCompany',
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object]
    },
    withPd: {
      type: Boolean,
      default: true
    },
    // placeholder
    placeholder: {
      type: String,
      default: function () {
        return '请选择'
      }
    },
    // 是否获取所有分公司
    getAll: {
      type: Boolean,
      default: () => false
    },
    // 是否获取登录人权限内的所有分公司，默认只获取岗位相关的分公司
    getAllBySelf: {
      type: Boolean,
      default: () => false
    },
    // 额外查询参数
    extraQuery: {
      type: Object,
      default() {
        return {}
      }
    },
    // 是否获取登录人权限内的公司，默认不获取
    isAddCO: {},
    // 是否自动选中第一行
    autoSelected: {
      type: Boolean,
      default: () => true
    },
    // 是否自动选中登录人所在公司
    isDefaultSelected: {
      type: Boolean,
      default: () => false
    },
    //隐藏自己所在的分公司 傻逼需求,不选不就行了吗
    hiddenSelfBran: {
      type: Boolean,
      default: () => false
    },
    //是否登录的是总公司,匹配不上去掉id
    isHeadOffice:{
       type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      fetching: false,
      company: [],
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info'))
    }
  },
  mounted() {
    this.getCompanyList()
  },
  methods: {
    getCompanyList() {
      if (this.withPd) {
        this.fetching = true
        const fn = this.getAll ? getAllBranchCompany : getCurrentUserBranchCom2 // 区分获取当前用户分公司，还是所有分公司
        // 若只获取登陆人当前岗位的分公司，则加参数
        if (!this.getAllBySelf) {
          this.extraQuery.tagCodes = ['BC']
        }

        fn(this.extraQuery)
          .then((res) => {
            this.fetching = false
            const list = res.data
            // 统一项目列表字段配置
            this.company = this.company.concat(
              this.getAll
                ? list?.map((item) => {
                    // 做返回值字段兼容处理
                    return {
                      ...item,
                      orgId: item.id,
                      orgName: item.name
                    }
                  })
                : list ?? []
            )
            //隐藏自己所在的分公司
            if (this.hiddenSelfBran) {
              this.company.splice(
                this.company.findIndex((item) => item.orgId === this.userInfo.currentPost.orgId),
                1
              )
            }
            // 当没有选中项时，若是登陆人权限列表、支持选中且列表第一项存在则添加默认值
            if (!this.currentValue && !this.getAll && this.autoSelected && this.company[0]?.orgId) {
              //默认选中后触发change事件
              let value = this.$attrs.hasOwnProperty('labelInValue') ? { key: this.company[0].orgId, label: this.company[0].orgName } : this.company[0].orgId // labelInValue存在时，返回labelInValue对象
              this.$emit('input', value)
              this.$emit('change', value)
              let res = this.company.find((v) => v.orgId === value)
              this.$emit('selectChange', res)
              this.$emit('autoBranchSelected', value)
              //   this.$emit('input', this.company[0].orgId)
            }
            if (this.isDefaultSelected) {
              let value = this.$attrs.hasOwnProperty('labelInValue') ? { key: this.userInfo.currentPost.orgId, label: this.userInfo.currentPost.orgName } : this.userInfo.currentPost.orgId // labelInValue存在时，返回labelInValue对象
              if(value==='53085e2c9f1f4685801ef31994f57c49' && this.isHeadOffice){
                 return false
              }
              this.$emit('input', value)
              this.$emit('change', value)
              let res = this.company.find((v) => v.orgId === value)
              this.$emit('selectChange', res)
              this.$emit('autoBranchSelected', value)
            }
          })
          .catch((res) => {
            this.fetching = false
            this.$message.warning(res?.data?.message || '系统错误!')
          })
      } else {
        this.getCompanyListWithEmployee()
        // 当没有选中项时，若是登陆人权限列表、支持选中且列表第一项存在则添加默认值
        if (!this.currentValue && !this.getAll && this.autoSelected && this.company[0]?.orgId) {
          this.$emit('input', this.company[0].orgId)
          this.$emit('autoBranchSelected', this.company[0].orgId)
          this.$emit('selectChange', this.company[0])
        }
      }
    },
    getCompanyListWithEmployee() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const employee = userInfo.employee || { levels: [] }
      const levels = employee.levels
      this.company = levels
        .filter((l) => l.code === 'BC')
        .map((l) => {
          return { orgId: l.id, orgName: l.name, orgCode: l.cod }
        })
    },
    getCOCompany() {
      getAllBranchCompany({ tagCodes: ['CO'] }).then((res) => {
        console.log(res)
        res.data = res.data.map((item) => {
          // 做返回值字段兼容处理
          return {
            ...item,
            orgId: item.id,
            orgName: item.name
          }
        })
        this.company.unshift(res.data[0])
        console.log(this.company)
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * 获取指定公司的name
     */
    getValueName(id) {
      const target = this.company.find((v) => v.orgId === id)
      console.log(target)
      return (target && target.orgName) || void 0
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        if(this.value==='53085e2c9f1f4685801ef31994f57c49' && this.isHeadOffice){
             return '';

        }else{
          return this.value
        }
      },
      set: function (value) {
        this.$emit('input', value)
        let res = this.company.find((v) => v.orgId === value)
        //和原生事件冲突
        this.$emit('selectChange', res)
      }
    }
  }
}
</script>
